import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/bean/list_app_article_basic_entity.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/ui/news/news_detail/news_detail_view.dart';
import 'package:flutter_app/utils/sp_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/values/CommonParam.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'search_state.dart';

class SearchLogic extends GetxController {
  final SearchState state = SearchState();

  RefreshController refreshController = RefreshController(initialRefresh: false);
  BrnSearchTextController searchController = BrnSearchTextController();
  TextEditingController textController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    getRecord();
  }


  @override
  void onReady() {
    super.onReady();
  }

  /// 获取效能动态
  Future<void> searchArticle(String text, {bool add = true}) async {
    if (text.isEmpty) {
      return toast.show("请输入要搜索的内容");
    }
    if (add) {
      addRecord(text, add);
    }
    Map<String, dynamic> param = {
      "currentPage": 1,
      "pageSize": 15,
      "param": {
        "articleType": "XNYW",
        "contentType": "",
        "isRotation": "",
        "keyword": text,
        "state": "",
      }
    };
    ResultData resultData = await Api.listAppArticleBasic(param);
    if (resultData.isSuccess) {
      state.listAppArticleBasicEntity = ListAppArticleBasicEntity.fromJson(resultData.data["data"]);
      if (state.listAppArticleBasicEntity?.content?.length == 0) {
        toast.show('未搜索到“$text”相关内容');
      }
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  // 获取历史记录
  void getRecord() async {
    String? record = await sp.getString(CommonParam.HISTORY_LIST);
    if (record != null) {
      state.historyList = record.split(", ");
      update();
    }
  }
  // 添加历史记录
  void addRecord(String text, bool add) {
    state.historyList.forEach((element) {
      if (text == element) {
        add = false;
      }
    });
    if (add) {
      state.historyList.add(text);
      sp.setString(CommonParam.HISTORY_LIST, state.historyList.toString().substring(1, state.historyList.toString().length-1));
      update();
    }
  }

  // 删除历史记录
  void deleteRecord() {
    print("deleteRecord");
    state.historyList.clear();
    sp.remove(CommonParam.HISTORY_LIST);
    update();
  }

  // 要闻 详情
  void goToNewsDetailPage(String? id) {
    Get.to(() => NewsDetailPage(title: '要闻详情',), arguments: id);
  }

  @override
  void onClose() {
    super.onClose();
    searchController.dispose();
    textController.dispose();
  }
}
